package com.qianxunclub.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by gunzi on 2017/2/21.
 */
public class HttpResponseUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpResponseUtil.class);

    protected HttpResponseUtil() {
    }

    public static void setResponseHtmlBody(HttpServletResponse resp, PageDataResponse baseResponse) {
        String responseStr = JsonUtil.objectToJson(baseResponse);
        setResponseBody(resp, responseStr, "text/html;charset=UTF-8", "UTF-8");
    }

    public static void setResponseJsonBody(HttpServletResponse resp, PageDataResponse baseResponse) {
        String responseStr = JsonUtil.objectToJson(baseResponse);
        setResponseBody(resp, responseStr, "application/json;charset=UTF-8", "UTF-8");
    }

    public static void setResponseHtmlBody(HttpServletResponse resp, BaseResponse baseResponse) {
        String responseStr = JsonUtil.objectToJson(baseResponse);
        setResponseBody(resp, responseStr, "text/html;charset=UTF-8", "UTF-8");
    }

    public static void setResponseJsonBody(HttpServletResponse resp, BaseResponse baseResponse) {
        String responseStr = JsonUtil.objectToJson(baseResponse);
        setResponseBody(resp, responseStr, "application/json;charset=UTF-8", "UTF-8");
    }

    public static void setResponseHtmlBody(HttpServletResponse resp, String respBodyStr) {
        setResponseBody(resp, respBodyStr, "text/html;charset=UTF-8", "UTF-8");
    }

    public static void setResponseJsonBody(HttpServletResponse resp, String respBodyStr) {
        setResponseBody(resp, respBodyStr, "application/json;charset=UTF-8", "UTF-8");
    }

    public static void setResponseBody(HttpServletResponse resp, String respBodyStr, String contentType, String encodingType) {
        resp.setCharacterEncoding(encodingType);
        resp.setContentType(contentType);
        PrintWriter printWriter = null;

        try {
            printWriter = resp.getWriter();
            printWriter.write(respBodyStr);
            printWriter.flush();
        } catch (IOException var9) {
            logger.error("HttpServletResponse写入异常" + var9.getMessage(), var9);
        } finally {
            if(printWriter != null) {
                printWriter.close();
            }

        }

    }
}
